from pptx import Presentation


def read_ppt_text(filepath):
    # 打开PPT文件
    presentation = Presentation(filepath)

    # 遍历每一张幻灯片
    for slide_number, slide in enumerate(presentation.slides, start=1):
        print(f"Slide {slide_number}:")

        # 遍历每个形状
        for shape in slide.shapes:
            # 检查形状是否包含文本框
            if shape.has_text_frame:
                for paragraph in shape.text_frame.paragraphs:
                    for run in paragraph.runs:
                        # 打印文本内容
                        print(run.text)

        print("-" * 40)  # 分隔符，便于阅读

from pptx import Presentation
from docx import Document


def clean_text(text):
    """
    移除不兼容XML的字符
    """
    # remove ASCII control characters and NULL bytes
    cleaned_text = re.sub(r'[\x00-\x1F\x7F]', '', text)
    return cleaned_text


def extract_text_from_ppt_to_word(ppt_file_path, word_file_path):
    # 加载PPT文件
    presentation = Presentation(ppt_file_path)

    # 创建一个新的Word文档
    doc = Document()

    # 遍历幻灯片
    for slide_number, slide in enumerate(presentation.slides, start=1):
        doc.add_heading(f'Slide {slide_number}', level=1)

        # 遍历每个形状
        for shape in slide.shapes:
            # 检查形状是否包含文本框
            if shape.has_text_frame:
                for paragraph in shape.text_frame.paragraphs:
                    cleaned_text = clean_text(paragraph.text)
                    # 添加每段清除后的文字到Word文档
                    doc.add_paragraph(cleaned_text)

                    # 加一个页面间的分隔符
        doc.add_page_break()

        # 保存Word文档
    doc.save(word_file_path)
    print(f"文字内容已经成功读取并保存到 {word_file_path}")


if __name__ == "__main__":
    ppt_file_path = "实验ppt读取文字.pptx"  # 替换为你的PPT文件路径
    word_file_path = "实验ppt读取文字.docx"  # 指定保存的Word文件路径
    extract_text_from_ppt_to_word(ppt_file_path, word_file_path)

"""if __name__ == "__main__":
    # filepath = "实验ppt读取文字.pptx"
    # read_ppt_text(filepath)
    ppt_file_path = "实验ppt读取文字.pptx"  # 替换为你的PPT文件路径
    word_file_path = "实验ppt读取文字.docx"  # 指定保存的Word文件路径
    extract_text_from_ppt_to_word(ppt_file_path, word_file_path)"""